package cn.msi.customer.service;

import java.util.Date;

import cn.common.manager.SessionManager;
import cn.common.util.GeneralUtils;
import cn.msi.customer.domain.User;
import cn.msi.customer.mapper.UserMapper;

/**
 * 用户业务处理
 * 
 * @author Administrator
 * 
 */
public class UserService {

	private UserMapper userMapper;

	/**
	 * 用户登陆业务处理方法
	 * 
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public String login(User user) throws Exception {
		Object code = SessionManager.getAttr("code");
		if (code != null && String.valueOf(code).equals(user.getValidatorCode())) {
			user = userMapper.selectByAccount(user);
			if (user != null) {
				SessionManager.setAttr("user", user);
				return "success";
			} else {
				return "loginError";
			}
		} else {
			return "codeError";
		}
	}

	/**
	 * 用户登出
	 * 
	 * @param user
	 * @return
	 */
	public String loginOut(User user) {
		SessionManager.remove();
		return "success";
	}

	/**
	 * 用户权限处理
	 * 
	 * @throws Exception
	 */
	public void handlerUser() throws Exception {

	}

	/**
	 * 查询客户的用户账号
	 * 
	 * @param user
	 * @return
	 */
	public String searchUserByCust(User user) {
		return GeneralUtils.easyUI(userMapper.count(user), userMapper.selectList(user));
	}

	/**
	 * 查找用户
	 * 
	 * @param user
	 * @return
	 */
	public User findUser(User user) {
		if (user.getUserId() != null) {
			user = userMapper.selectByUserId(user.getUserId());
		}
		return user;
	}

	/**
	 * 编辑用户信息
	 * 
	 * @param user
	 */
	public void editUser(User user) {
		if (user.getUserId() != null) {
			userMapper.update(user);
		} else {
			user.setUserType("W");
			user.setPassword("123456");
			user.setCreateTime(new Date());
			user.setUserState("S");
			userMapper.insert(user);
		}
	}

	/**
	 * 删除用户账号
	 * 
	 * @param user
	 */
	public void deleteUser(User user) {
		user.setUserState("D");
		userMapper.update(user);
	}

	/**
	 * 查询用户
	 * 
	 * @return
	 */
	public String userSearchList(User user) {
		User u = (User) SessionManager.getAttr("user");
		user.setCustId(u.getCustId());
		return GeneralUtils.easyUI(userMapper.count(user), userMapper.selectList(user));
	}

	/**
	 * 保存用户账户
	 * 
	 * @param user
	 */
	public void userSave(User user) {
		if (user.getUserId() != null) {
			userMapper.update(user);
		} else {
			User u = (User) SessionManager.getAttr("user");
			user.setCustId(u.getCustId());
			user.setPassword("123456");
			user.setCreateTime(new Date());
			user.setUserState("S");
			userMapper.insert(user);
		}
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}
}
